import 'dart:core';
import 'dart:core';
import 'package:flutter/cupertino.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:flutter/material.dart';
import 'package:demo1/dto/district.dart';
import 'package:demo1/dto/districtApi.dart';
import 'package:demo1/util/GraphqlUtil.dart';

//* 地区详情页面
//有两个入口可以进来此页面（列表页的编辑按钮， 列表页右下角的新增按钮， 区别是前者带参id， 后者不带参）
class DistrictDetailPage extends StatefulWidget {
  String id = '';

  DistrictDetailPage({Key key, this.id}) : super(key: key);

  @override
  _DistrictDetailPageState createState() => _DistrictDetailPageState();
}

class _DistrictDetailPageState extends State<DistrictDetailPage> {
  @override
  Widget build(BuildContext context) {
    final districtId = widget.id;
    return Scaffold(
        appBar: AppBar(
          title: Text("编辑地区信息"),
          centerTitle: true,
        ),
        body: new GestureDetector(
          //加这个组件是为了点击不属于输入框的区域时， 键盘可以自动退下
          onTap: () {
            FocusScope.of(context).requestFocus(new FocusNode());
          },

          //创建详情页
          child: Container(
            padding: EdgeInsets.all(32),
            child: GraphQLProvider(
              child: ShowPge(districtId: districtId),
              client: clientNotifiler,
            ),
          ),
        ));
  }
}

//创建详情页
class ShowPge extends StatefulWidget {
  final String districtId;

  ShowPge({Key key, this.districtId}) : super(key: key);

  @override
  _showPgeState createState() => _showPgeState();
}

class _showPgeState extends State<ShowPge> {
  District district;

  @override
  Widget build(BuildContext context) {
    //如果当前页面的districtId不存在， 表示为新增操作， 直接开始渲染空页面
    if (widget.districtId == null) {
      return CreateDetail();
    }

    //如果当前页面的districtId存在， 先用gql调用后台， 根据id查询地区的详情信息， 开始填充渲染页面
    return Query(
        options: QueryOptions(
            documentNode: gql(DistrictApi.getDistrictById(widget.districtId))),
        builder: (QueryResult result, {Refetch refetch, FetchMore fetchMore}) {
          if (result.loading) {
            //拿不到结果转圈圈
            return Center(child: CircularProgressIndicator());
          }
          //取得结果反转json为对象
          district = District.fromJson(result.data['district']);
          //根据查询得到的地区信息填充页面
          return CreateDetail(district: district);
          // return _createDetail(district: district);
        });
  }
}

class CreateDetail extends StatefulWidget {
  District district;

  CreateDetail({Key key, this.district}) : super(key: key);

  @override
  _CreateDetailState createState() => _CreateDetailState();
}

class _CreateDetailState extends State<CreateDetail> {
  //*输入框控制器
  TextEditingController txtNameController = TextEditingController();
  List<TextEditingController> txtAddressController = List();
  TextEditingController txtPackController = TextEditingController();
  TextEditingController txtDeliveryController = TextEditingController();


  //*使用后台查询得到的地区信息初始化输入框的值
  @override
  void initState() {
    super.initState();
    txtNameController.text = (widget.district == null || widget.district.name == null)
        ? ''
        : widget.district.name;
    if (widget.district != null && widget.district.address != null) {
      widget.district.address.forEach((element) {
        txtAddressController.add(new TextEditingController(text: element));
      });
    };
    txtPackController.text =
        (widget.district == null || widget.district.packagingFactor == null)
            ? ''
            : widget.district.packagingFactor.toString();
    txtDeliveryController.text =
        (widget.district == null || widget.district.deliveryFactor == null)
            ? ''
            : widget.district.deliveryFactor.toString();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          CreateRow(
              label: '地区 :',
              controller: txtNameController,
              value: widget.district == null ? '' : widget.district.name),
          Divider(),
          Row(
            children: [
              Text("地址： ",style: TextStyle(color: Colors.black),),
              Flexible(child: CreateTags(tags: (widget.district == null || widget.district.address== null) ? new List() : widget.district.address,txtAddressController:txtAddressController)),
            ],
          ),
          // CreateRow(label: '地址 :', controller : txtAddress,
          //     value: (widget.district == null || widget.district.address == null) ? '' :widget.district.address.toString(), dropdown: true),
          Divider(),
          CreateRow(
              label: 'pack :',
              controller: txtPackController,
              value: widget.district == null
                  ? ''
                  : widget.district.packagingFactor,
              type: 'num'),
          Divider(),
          CreateRow(
              label: 'deliver :',
              controller: txtDeliveryController,
              value:
                  widget.district == null ? '' : widget.district.deliveryFactor,
              type: 'num'),
          Divider(),
          // _createRow('更新時間 :'),
          // Divider(),
          // _createRow('创建时间 :'),
          // Divider(),

          //* 点击保存按钮时，读取控制器的内容，调用后台接口， 发起保存请求
          SubmitButton(
            onPressed: () {
              if (txtNameController.text == '') {
                print("地区名称不能为空！");
              }
              District newDistrict = new District(id:widget.district == null ? "" : widget.district.id,name: txtNameController.text,
                      address: txtAddressController.map((e) => e.text).toList(), packagingFactor: double.parse(txtPackController.text),
                      deliveryFactor:  double.parse(txtDeliveryController.text));

              //新增
              if (widget.district == null) {
                client.mutate(MutationOptions(
                    documentNode: gql(DistrictApi.create(newDistrict.toJson()))))
                    .then((value) => {
                  if (value.hasException)
                    {
                      throw value.exception,
                    }
                });
              } else {
                //更新
                client.mutate(MutationOptions(
                    documentNode: gql(
                        DistrictApi.update(newDistrict.toJson()))))
                    .then((value) =>
                {
                  if (value.hasException)
                    {
                      throw value.exception,
                    }
                });
              }
            },
            text: '保存',
          ),
        ],
      ),
    );
  }
}

//*创建tags
class CreateTags extends StatefulWidget {
  List<String> tags;
  double minTagViewHeight;
  double maxTagViewHeight;
  List<TextEditingController> txtAddressController;

  CreateTags({Key key, this.tags,this.txtAddressController, this.minTagViewHeight:50, this.maxTagViewHeight:250})
      : super(key: key);

  @override
  _CreateTagsState createState() => _CreateTagsState();
}

class _CreateTagsState extends State<CreateTags> {

  TextEditingController addressController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return ConstrainedBox(
      constraints: BoxConstraints(
          minHeight: widget.minTagViewHeight,
          maxHeight: widget.maxTagViewHeight),
      child: SingleChildScrollView(
        child: Wrap(
          alignment: WrapAlignment.start,
          spacing: 5,
          direction: Axis.horizontal,
          children: buildTags(),
        ),
      ),
    );
  }

  //*创建tag项
  List<Widget> buildTags() {
    List<Widget> tags = <Widget>[];
    for (int i = 0; i < widget.tags.length; i++) {
      tags.add(createSingleTag(i, widget.tags[i], Icon(Icons.cancel)));
    }
    tags.add(createSingleTag(widget.tags.length,'新增地址',Icon(Icons.add_circle, color: Colors.white,), backColor:Colors.black));
    return tags;
  }

  Widget createSingleTag(int index, String tagTitle,Icon icon,{ Color backColor}) {

    TextEditingController controller = new TextEditingController();

    return InkWell(
      onTap: () {

      },
      child: Chip(
        backgroundColor:backColor,
        label: Text(tagTitle, style: TextStyle(color: index == widget.tags.length ? Colors.white70 : null),),
        deleteIcon: icon,
        onDeleted: () {
          //点击新增按钮
          if (index == widget.tags.length) {
            showDialog(
              context: context,
              child: new AlertDialog(
                content: TextField(
                  controller: controller,
                  autofocus: true,
                ),
                actions: <Widget>[
                  new FlatButton(
                      onPressed: () {
                        setState(() {
                          // widget.tags.add('小小玉');
                          widget.tags.add(controller.text);
                          widget.txtAddressController.add(controller);
                        });
                        Navigator.pop(context);
                      },
                      child: Text('确定',style: TextStyle(color: Theme.of(context).primaryColor),)),
                  new FlatButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text('取消', style: TextStyle(color: Theme.of(context).primaryColor),))
                ],

              ),
            );
          } else {
            setState(() {
              // widget.tags.add('小小玉');
              widget.tags.removeAt(index);
              widget.txtAddressController.removeAt(index);
            });
          }
        },
      ),
    );
  }
}

//创建详情页的每一行表单信息
class CreateRow extends StatefulWidget {
  String label;
  TextEditingController controller;
  var value;
  bool dropdown;
  String type; //输入框支持的格式， num表示为只可输入数字

  CreateRow(
      {Key key,
      this.label,
      this.controller,
      this.value,
      this.dropdown: false,
      this.type})
      : super(key: key);

  @override
  _CreateRowState createState() => _CreateRowState();
}

class _CreateRowState extends State<CreateRow> {
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text(widget.label, style: TextStyle(color: Colors.black, fontSize: 18)),
        Expanded(
            child: TextFormField(
          controller: widget.controller,
          cursorColor: Colors.black,
          keyboardType:
              widget.type == 'num' ? TextInputType.number : TextInputType.text,
          decoration: const InputDecoration(
            border: InputBorder.none,
            focusedBorder: InputBorder.none,
            enabledBorder: InputBorder.none,
            disabledBorder: InputBorder.none,
            contentPadding: EdgeInsets.all(8),
// hintText: '输入正确的地区信息',
// labelText: '地区 *'
          ),
          validator: (String value) {
            return value.length > 20 ? '名称过长' : null;
          },
        ))
      ],
    );
  }
}

//提交按钮
class SubmitButton extends StatelessWidget {
  final VoidCallback onPressed;

  final String text;

  SubmitButton({@required this.onPressed, this.text: '提交'});

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      color: Colors.deepOrange,
      elevation: 4,
      onPressed: () {
        onPressed();
        Scaffold.of(context).showSnackBar(
          SnackBar(
              content: Row(
                children: [
                  Icon(Icons.check),
                  Text(
                    '保存成功!',
                    style: TextStyle(color: Colors.white),
                  ),
                ],
              ),
              duration: Duration(seconds:1),
              backgroundColor: Theme.of(context).primaryColor),
        );
        // _submitData(txtName.value.text);
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: Text(
        text,
        style: TextStyle(color: Colors.white),
      ),
    );
  }

/*void _submitData(String val) {
    // print(val);
    Scaffold.of(context).showSnackBar(
      SnackBar(content: Text('保存成功!')),
    );
  }*/
}
